//
//  HomePageView.swift
//  Chatup
//
//  Created by op on 2023/10/17.
//

import FirebaseAnalytics
import Kingfisher
import SwiftUI

struct CornerMaskShape: Shape {
    func path(in rect: CGRect) -> Path {
        var path = Path(roundedRect: rect, cornerRadius: 12)

        // Define the area to keep as a square
        let maskRect = CGRect(x: rect.origin.x, y: rect.origin.y, width: 12, height: 12)

        // Subtract the square path from the RoundedRectangle path
//        if let maskPath = Path(ellipseIn: maskRect) {
        if #available(iOS 17.0, *) {
            path = path.subtracting(Path(ellipseIn: maskRect))
        } else {
            // Fallback on earlier versions
        }
//        }

        return path
    }
}

struct HomePageHeaderItem: View {
    @State var imageString: String
    var body: some View {
        ZStack(alignment: .bottomTrailing) {
            Image(imageString)
                .resizable()
                .frame(width: 24, height: 24)
                .overlay(
                    RoundedRectangle(cornerRadius: 12)
                        .stroke(Color.black, lineWidth: 3)
                )
            Image("icon_online")
                .resizable()
                .frame(width: 8, height: 8)
        }
    }
}

struct HomePageHeaderItem2: View {
    @State var model: TempModel
//    @State var imageString:String
    var body: some View {
        ZStack(alignment: .bottomTrailing) {
            Image(model.icon)
                .resizable()
                .frame(width: 36, height: 36)
//                .overlay(
//                    RoundedRectangle(cornerRadius: 18)
            ////                        .stroke(Color.black, lineWidth: 3)
//                )
            Image("icon_online")
                .resizable()
                .frame(width: 8, height: 8)
        }
    }
}

struct RoundedCorner: Shape {
    var radius: CGFloat = .infinity
    var corners: UIRectCorner = .allCorners

    func path(in rect: CGRect) -> Path {
        let path = UIBezierPath(roundedRect: rect, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        return Path(path.cgPath)
    }
}

extension View {
    func cornerRadius(_ radius: CGFloat, corners: UIRectCorner) -> some View {
        clipShape(RoundedCorner(radius: radius, corners: corners))
    }
}

struct ToastView: View {
    let text: String

    var body: some View {
        VStack {
            Text(text)
                .font(.system(size: 13))
                .padding()
                .background(Color.black)
                .foregroundColor(.white)
                .cornerRadius(10)
                .padding(.top, 30) // Adjust this value for the top margin
                .opacity(0.8)
        }
    }
}

struct HomePageViewHeader: View {
    @State var choosed: TempModel
    @State var rolelist: [TempModel]
    var ontapList: () -> Void
    var body: some View {
        HStack {
            HomePageHeaderItem2(model: choosed)
            Spacer()
                .frame(width: 10)
            VStack(alignment: .leading) {
                Text(choosed.name)
                    .font(.system(size: 16))
                    .foregroundColor(.white)
                Text(choosed.desc)
                    .font(.system(size: 12))
                    .foregroundColor(.white.opacity(0.5))
            }
            Spacer()
            Button(action: {
                ontapList()
            }, label: {
                HStack(spacing: 0) {
                    HStack(spacing: -2) {
                        ForEach(rolelist.indices, id: \.self) { index in
                            ZStack(alignment: .bottomTrailing) {
                                Image(rolelist[index].icon)
                                    .resizable()
                                    .frame(width: 24, height: 24)
                                    .overlay(
                                        RoundedRectangle(cornerRadius: 12)
                                            .stroke(Color.black, lineWidth: 3)
                                    )
                                Image("icon_online")
                                    .resizable()
                                    .frame(width: 8, height: 8)
                            }
                        }
                    }
                    Image("icon_right")
                        .resizable()
                        .frame(width: 20, height: 20)
                }
            })
        }
    }
}

struct CustomTextFieldStyle: TextFieldStyle {
    @FocusState var isFocused: Bool
    @Binding var hasMsg: Bool
    func _body(configuration: TextField<_Label>) -> some View {
        configuration
            .padding(12)
            .background(RoundedRectangle(cornerRadius: 12).fill(hasMsg || isFocused ? Color(red: 0.21, green: 0.84, blue: 0.54).opacity(0.1) : Color.white.opacity(0.1)))
            .overlay(
                RoundedRectangle(cornerRadius: 12)
                    .inset(by: 0.25)
                    .stroke(Color(red: 0.21, green: 0.84, blue: 0.54))
            )
            .focused($isFocused)
            .foregroundColor(.white)
            .font(.system(size: 14))
//            .padding(.horizontal, 10)
    }
}

struct HomePageView: View {
    @StateObject var viewModel = HomePageViewModel()
    @Binding var section: ContentView.Tab
    @State var newMessage: String = ""
    @FocusState private var isFocused: Bool
    @Binding var item: MsgItem
    @Binding var historyItemRoleId: Int
    @State var chooseDialogItem: Int = -1
    @State var showVIP = false
    @State private var showToast = false
    @State private var showMsgToast = false
    @State var hasMsg = false
    @State var textEditorHeight: CGFloat = 40
    @State private var isShowingDetailView = false
    @State private var image = ""
    @State private var showingSheet = false

    @State private var showWhiteView = false
    @State private var whiteViewOffset = CGSize.zero

    @State private var showModeView = false

    @State private var modeViewOffset = CGSize.zero
    @State private var showDrawImageView = false
    @State private var showRecognizeImagesView = false
    @State private var showSummarizeDocumentView = false
    @State private var showAnalyzeLinkView = false
    @State private var showTranslateView = false
    @State private var showEmojiView = false
    @State private var isShowingShareView = false
    @State private var showDrawImageToast = false
    @State private var isFinish = true
    @State private var sheetHeight: CGFloat = .zero
    var body: some View {
        GeometryReader(content: { _ in
            ZStack {
                VStack(spacing: 0) {
                    HStack {
                        Button {
                            self.showModeView.toggle()
                        } label: {
                            if !viewModel.isVip {
                                Image("")
                                    .resizable()
                                    .frame(width: 77, height: 24)
                            }
                            Spacer()
                            if viewModel.isVip && viewModel.mode == "gpt4" {
                                Text("GPT 4.0")
                                    .font(.system(size: 20, weight: .bold))
                                    .foregroundColor(.white)
                            } else {
                                Text("GPT 3.5")
                                    .font(.system(size: 20, weight: .bold))
                                    .foregroundColor(.white)
                            }
                            Spacer().frame(width: 12)
                            Image("ic_translate_bottom")
                                .resizable()
                                .frame(width: 8, height: 8)
                            Spacer()
                            if !viewModel.isVip {
                                Image("icon_setting_vip_right")
                                    .resizable()
                                    .frame(width: 77, height: 24).onTapGesture {
                                        showVIP.toggle()
                                    }
                            }
                        }
                    }
                    .padding(.horizontal)
                    .padding(.vertical, 8)
                    VStack(alignment: .leading, spacing: 0) {
                        HStack {
                            ZStack(alignment: .bottomTrailing) {
                                Image(viewModel.choosed.icon)
                                    .resizable()
                                    .frame(width: 36, height: 36)
                                Image("icon_online")
                                    .resizable()
                                    .frame(width: 8, height: 8)
                            }
                            Spacer()
                                .frame(width: 10)
                            VStack(alignment: .leading) {
                                Text(viewModel.choosed.name)
                                    .font(.system(size: 16))
                                    .foregroundColor(.white)
                                Text(viewModel.choosed.desc)
                                    .font(.system(size: 12))
                                    .foregroundColor(.white.opacity(0.5))
                            }
                            Spacer()
                            Button(action: {
                                if section == .second {
                                    section = .third
                                } else {
                                    viewModel.logClickCharaters()
                                    viewModel.showDialog.toggle()
                                }
                            }, label: {
                                HStack(spacing: 0) {
                                    HStack(spacing: -2) {
                                        ForEach(viewModel.roleList.indices, id: \.self) { index in
                                            ZStack(alignment: .bottomTrailing) {
                                                Image(viewModel.roleList[index].icon)
                                                    .resizable()
                                                    .frame(width: 24, height: 24)
                                                    .overlay(
                                                        RoundedRectangle(cornerRadius: 12)
                                                            .stroke(Color.black, lineWidth: 3)
                                                    )
                                                Image("icon_online")
                                                    .resizable()
                                                    .frame(width: 8, height: 8)
                                            }
                                        }
                                    }
                                    Image("icon_right")
                                        .resizable()
                                        .frame(width: 20, height: 20)
                                }
                            })
                        }
                        Spacer()
                            .frame(height: 12)
                    }
                    .padding([.top, .bottom], 0)
                    .padding([.trailing, .leading], 16)
                    Divider()
                    ScrollViewReader { scrollViewProxy in
                        ScrollView {
                            Spacer()
                                .frame(height: 16)
                            ForEach(viewModel.messages, id: \.id) { message in
                                ChatBubbleView(isVip: viewModel.isVip, model: message
                                               , showToast: $showToast)
                                .id(message.id)
                                    .padding(.vertical, 5)
                                    .padding(.horizontal, 16)
                                    .sheet(isPresented: $isShowingDetailView) {
                                        ImageDetailView(image: $image)
                                    }
                            }
                        }
                        .onAppear {
                            viewModel.initData()
                            scrollViewProxy.scrollTo(viewModel.messages.last?.id)
                        }
                        .onChange(of: viewModel.messages.count) { _ in
                            withAnimation {
                                scrollViewProxy.scrollTo(viewModel.messages.last?.id, anchor: .bottom)
                            }
                        }
                        .onChange(of: viewModel.outputMsg, perform: { _ in
//                            if value {
                            withAnimation {
                                scrollViewProxy.scrollTo(viewModel.messages.last?.id, anchor: .bottom)
                            }
//                            }
                        })
                        .onTapGesture {
                            isFocused = false
                        }
                    }.overlay(
                        showModeView ? Color.black.opacity(0.1).frame(maxWidth: .infinity, maxHeight: .infinity)
                            .onTapGesture {
                                showModeView = false
                            }.overlay(
                                modeView,
                                alignment: .topLeading
                            ) : nil
                    ).sheet(isPresented: $isShowingShareView) {
                        ShareView()
                    }

                    Divider()

                    Spacer()
                        .background(Color(red: 15/255.0, green: 15/255.0, blue: 17/255.0))
                        .frame(height: 8)

                    HStack(alignment: .center) {
                        Button(action: {
                            self.showWhiteView.toggle()
                        }, label: {
                            VStack(spacing: 0) {
                                Image("ic_mofabang")
                                    .resizable()
                                    .frame(width: 25, height: 25)
                            }
                        }).sheet(isPresented: $showTranslateView) {
                            TranslateView().presentationDetents([.height(566)])
                        }.sheet(isPresented: $showEmojiView) {
                            EmojiView().presentationDetents([.height(566)])
                        }.sheet(isPresented: $showDrawImageView) {
                            DrawImaginationView().presentationDetents([.height(492)])

                        }.sheet(isPresented: $showRecognizeImagesView) {
                            RecognizeImagesView().presentationDetents([.height(566)])
                        }.sheet(isPresented: $showSummarizeDocumentView) {
                            DocumentView().presentationDetents([.height(566)])

                        }.sheet(isPresented: $showAnalyzeLinkView) {
                            LinkView().presentationDetents([.height(566)])
                        }

                        TextField(String.i18nText("chat_ask"), text: $newMessage)
                            .background(Color(red: 15/255.0, green: 15/255.0, blue: 17/255.0))
                            .font(.system(size: 14))
                            .textFieldStyle(CustomTextFieldStyle(hasMsg: $hasMsg))
                            .cornerRadius(12)
                            .focused($isFocused)
                            .padding(.vertical, 0)

                        Button(action: {
                            if !viewModel.isVip, viewModel.currentRole?.roleType != RoleModelType.bot.rawValue {
                                showVIP.toggle()
                                return
                            }
                            debugPrint(viewModel.messages.last!.isFinish)
                            if !viewModel.messages.last!.isFinish && viewModel.messages.last!.messageType == .text && !viewModel.messages.last!.isUser{
                                return
                            }
                            if newMessage.allSatisfy({ $0.isWhitespace }) {
                                return
                            }

                            if !viewModel.isVip {
                                if viewModel.leftCount == 0 {
                                    viewModel.logFrom = "chat_send"
                                    viewModel.showGpt3VipTips = true
                                    UserDefaults.standard.setValue(true, forKey: "gpt3oversize")
                                    UserDefaults.standard.synchronize()
                                    showVIP.toggle()
                                    return
                                }
                            }
                            viewModel.refreshUI(msg: newMessage)
                            newMessage = ""
                        }, label: {
                            Image(isFocused || hasMsg ? "icon_chat_bottom_send_green" : "icon_chat_bottom_send_gray")
                                .resizable()
                                .frame(width: 24, height: 24)
                        })
                    }
                    .padding([.top, .bottom], 0)
                    .padding([.trailing, .leading], 16)
                    Spacer()
                        .background(Color(red: 15/255.0, green: 15/255.0, blue: 17/255.0))
                        .frame(height: 8)
                    Divider()
                }

                if viewModel.newUser {
                    VStack(alignment: .trailing, spacing: 20) {
                        Spacer()
                        ForEach(viewModel.quickItems.indices, id: \.self) { index in
                            Button(action: {
//                                if newMessage.allSatisfy({ $0.isWhitespace }){
//                                    return
//                                }

                                if !viewModel.isVip {
                                    if viewModel.leftCount == 0 {
                                        viewModel.showGpt3VipTips = true
                                        UserDefaults.standard.setValue(true, forKey: "gpt3oversize")
                                        UserDefaults.standard.synchronize()
                                        showVIP.toggle()
                                        return
                                    }
                                }
                                viewModel.refreshUI(msg: viewModel.quickItems[index].name)
                            }, label: {
                                HStack {
                                    Spacer()
                                    VStack {
                                        Text(viewModel.quickItems[index].name)
                                            .font(.system(size: 14))
                                    }
                                    .padding(10)
                                    .background(Color(red: 32/255.0, green: 37/255.0, blue: 35/255.0))
                                    .foregroundColor(.white)
                                    .cornerRadius(8)
                                    Spacer()
                                        .frame(width: 12)
                                }
                            })
                        }
                        HStack {
                            Spacer()

                            Button(action: {
                                viewModel.refreshProData()
                            }, label: {
                                HStack {
                                    Image("icon_refresh")
                                    Spacer().frame(width: 4)
                                    Text(String.i18nText("chat_more"))
                                        .lineLimit(1)
                                        .font(Font.system(size: 12))
                                        .foregroundColor(Color(red: 0.53, green: 0.55, blue: 0.59))
                                }.frame(height: 40)
                                    .aspectRatio(contentMode: .fit)
                            })
                            Spacer()
                                .frame(width: 12)
                        }
                        Spacer()
                            .frame(height: 40)
                    }
                }

                if viewModel.showDialog {
                    HomeDialogView(showDialog: $viewModel.showDialog, chooseDialogIndex: $chooseDialogItem, curRoleId: viewModel.currentRole?.id ?? 0)
                }

                if viewModel.showGpt3VipTips{
                    ZStack {
                        Spacer()
                        VStack (spacing: 0){
                            Spacer().background(.red)
                            HStack {
                                VStack (spacing: 0){
                                    HStack{
                                        Text(String.i18nText("chat_no_credit_gpt3.5"))
                                            .font(Font.system(size: 14, weight: .semibold))
                                            .foregroundColor(.white)
                                            
                                    }.frame(height: 100)
                                        .frame(maxWidth:.infinity)
                                        .padding(.horizontal, 12)
                                        .background(Color(red: 0.15, green: 0.15, blue: 0.2))
                                        .cornerRadius(12, corners: .topLeft)
                                        .cornerRadius(12, corners: .topRight)

                                    HStack{
                                        Text("🌟")
                                            .font(Font.system(size: 14, weight: .semibold))
                                            .foregroundColor(.white)
                                        Spacer().frame(width: 12)
                                        Text(String.i18nText("subs_try_for_free"))
                                            .font(Font.system(size: 14, weight: .semibold))
                                            .foregroundColor(.white)
                                        Spacer()
                                        Image("ic_right")
                                            .resizable()
                                            .frame(width: 24, height: 24)
                                    }.frame(height: 46)
                                        .padding(.horizontal, 12)
                                        .background(Color(red: 0.21, green: 0.84, blue: 0.54))
                                        .cornerRadius(12, corners: .bottomLeft)
                                        .cornerRadius(12, corners: .bottomRight)

                                }.frame( maxWidth:.infinity)
                                    .padding(.horizontal, 12)
                                    .padding(.bottom, 60)
                                    .onTapGesture {
                                        if viewModel.isVip{
                                            viewModel.mode = "gpt4"
                                            UserDefaults.standard.setValue("gpt4", forKey: "mode")
                                            UserDefaults.standard.synchronize()
                                            viewModel.showGpt3VipTips = false
                                            UserDefaults.standard.setValue(false, forKey: "gpt3oversize")
                                            UserDefaults.standard.synchronize()
                                        }else{
                                            viewModel.logFreeClick()
                                            viewModel.logFrom = "chat_free"
                                            showVIP.toggle()
                                        }
                                    }

                            }
                        }
                    }
                    .frame(maxWidth: .infinity, maxHeight: .infinity).onAppear {
                        viewModel.logFreeShow()
                    }
                }
                if viewModel.showGpt4VipTips{
                    ZStack {
                        Spacer()
                        VStack {
                            Spacer().background(.red)
                            HStack {
                                VStack(spacing: 0) {
                                    HStack{
                                        Text(String.i18nText("chat_no_credit_gpt4.0"))
                                            .font(Font.system(size: 14, weight: .semibold))
                                            .foregroundColor(.white)
                                        }
                                        .frame(height: 100)
                                        .frame(maxWidth:.infinity)
                                        .padding(.horizontal, 12)
                                        .background(Color(red: 0.15, green: 0.15, blue: 0.2))
                                        .cornerRadius(12, corners: .topLeft)
                                        .cornerRadius(12, corners: .topRight)

                                    HStack(spacing: 0) {
                                        Text("🌟")
                                            .font(Font.system(size: 14, weight: .semibold))
                                            .foregroundColor(.white)
                                        Spacer().frame(width: 12)
                                        Text(String.i18nText("chat_no_credit_gpt4.0_swich"))
                                            .font(Font.system(size: 14, weight: .semibold))
                                            .foregroundColor(.white)
                                        Spacer()
                                        Image("ic_right")
                                            .resizable()
                                            .frame(width: 24, height: 24)
                                    }.frame(height: 46)
                                        .padding(.horizontal, 12)
                                        .background(Color(red: 0.21, green: 0.84, blue: 0.54))
                                        .cornerRadius(12, corners: .bottomLeft)
                                        .cornerRadius(12, corners: .bottomRight)

                                }.frame( maxWidth:.infinity)
                                    .padding(.horizontal, 12)
                                    .padding(.bottom, 60)
                                    .onTapGesture {
                                        viewModel.showGpt4VipTips = false
                                        UserDefaults.standard.setValue(false, forKey: "gpt4oversize")
                                        UserDefaults.standard.synchronize()
                                        viewModel.mode = "gpt3"
                                        UserDefaults.standard.setValue("gpt3", forKey: "mode")
                                        UserDefaults.standard.synchronize()
                                        viewModel.overMsgCount = false
                                    }

                            }
                        }
                    }
                    .frame(maxWidth: .infinity, maxHeight: .infinity).onAppear {
                        viewModel.logFreeShow()
                    }
                }

                if showToast {
                    ToastView(text: "Success!")
                }

                if showMsgToast {
                    ToastView(text: "The previous chat is still in progress, please wait")
                }
                
                if showDrawImageToast{
                    ToastView(text: String.i18nText("feature_draw_imagination_no_credit"))
                }
            }

        }).overlay(
            showWhiteView ? Color.black.opacity(0.1).frame(maxWidth: .infinity, maxHeight: .infinity)
                .onTapGesture {
                    viewModel.logFeaturesClick()
                    showWhiteView = false
                }.overlay(
                    featuresView,
                    alignment: .bottomLeading
                ) : nil
        )
        .onChange(of: item, perform: { value in
            if !viewModel.messages.last!.isFinish && viewModel.messages.last!.messageType == .text && !viewModel.messages.last!.isUser {
                self.showMsgToast.toggle()
                hideToastAfterDelay()
                return
            }
            viewModel.refreshUI(msg: value.text)
        })
        .onReceive(NotificationCenter.default.publisher(for: Notification.Name("kRefreshMsg"))) { _ in
//            debugPrint("value")
        }
        .onReceive(NotificationCenter.default.publisher(for: Notification.Name("kUpdateLaseMessage"))) { notification in
            let data = notification.object as? MessageModel
            if data != nil && (data!.roleId == nil || data!.roleId == "0"){
                viewModel.messages.removeLast()
                viewModel.messages.append(data!)
                viewModel.outputMsg = viewModel.outputMsg + 1
            }
        }.onReceive(NotificationCenter.default.publisher(for: Notification.Name("refreshVip"))) { _ in
            viewModel.refreshVip()
        }.onReceive(NotificationCenter.default.publisher(for: Notification.Name("kScrollToBottom"))) { notification in
            let data = notification.object as? MessageModel
            if data != nil && (data!.roleId == nil || data!.roleId == "0"){
                withAnimation {
                    viewModel.outputMsg = viewModel.outputMsg + 1
                }
            }
        }.onReceive(NotificationCenter.default.publisher(for: Notification.Name("kAppendMessage"))) { notification in
            // 在这里处理通知
            DispatchQueue.main.async {
                section = .second
                let data = notification.object as? [String: Any]
                let messages = data?["msgs"] as? [MsgModel]
                let feature = data?["feature"] as? FeaturesType
                let roleId = data?["roleId"] as? String
                if roleId != nil && roleId != "0"{
                    return
                }
                let curMode = viewModel.mode
                if feature == .link {
                    viewModel.mode = "gpt4"
                    UserDefaults.standard.setValue("gpt4", forKey: "mode")
                    UserDefaults.standard.synchronize()
                }
                viewModel.appendMessage(msgs: messages ?? [],feature: feature ?? .talk)
                if feature == .link {
                    viewModel.mode = curMode
                    UserDefaults.standard.setValue(curMode, forKey: "mode")
                    UserDefaults.standard.synchronize()
                }
            }
        }.onReceive(NotificationCenter.default.publisher(for: Notification.Name("kCopyMessage"))) { notification in
            let model = notification.object as! MessageModel
            if (model.roleId == nil || model.roleId != String(0)){
                return
            }
            let pasteboard = UIPasteboard.general
            pasteboard.string = model.message
            showToast.toggle()
            Analytics.logEvent("chat_answers_copy", parameters: nil)
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                withAnimation {
                    showToast.toggle()
                }
            }
            
        }.onReceive(NotificationCenter.default.publisher(for: Notification.Name("kReaskMessage"))) { notification in
            //            debugPrint("value")
            let model = notification.object as! MessageModel
            if (model.roleId == nil || model.roleId != String(0)){
                return
            }
            viewModel.logReaskClick()
            viewModel.refreshUI(msg: model.message)
        }.onReceive(NotificationCenter.default.publisher(for: Notification.Name("kShareMessage"))) { _ in
            isShowingShareView.toggle()
        }.onReceive(NotificationCenter.default.publisher(for: Notification.Name("kDrawImageOverSizeMessage"))) { _ in
            viewModel.messages.removeLast()
            showDrawImageToast.toggle()
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                withAnimation {
                    showDrawImageToast = false
                }
            }
        }.onReceive(NotificationCenter.default.publisher(for: Notification.Name("kGpt3OverSizeMessage"))) { _ in
            viewModel.messages.removeLast()
            if !viewModel.isVip{
                viewModel.leftCount = 0
                UserDefaults.standard.setValue(0, forKey: "leftCount")
                UserDefaults.standard.synchronize()
            }
            if !viewModel.showGpt3VipTips{
                viewModel.showGpt3VipTips.toggle()
                UserDefaults.standard.setValue(true, forKey: "gpt3oversize")
                UserDefaults.standard.synchronize()
            }
        }.onReceive(NotificationCenter.default.publisher(for: Notification.Name("kGpt4OverSizeMessage"))) { _ in
            viewModel.messages.removeLast()
            if !viewModel.isVip{
                viewModel.leftCount = 0
                UserDefaults.standard.setValue(0, forKey: "leftCount")
                UserDefaults.standard.synchronize()
            }
            if !viewModel.showGpt4VipTips{
                viewModel.showGpt4VipTips.toggle()
                UserDefaults.standard.setValue(true, forKey: "gpt4oversize")
                UserDefaults.standard.synchronize()
            }
        }.onReceive(NotificationCenter.default.publisher(for: Notification.Name("kOpenImageMessage"))) { notification in
            let model = notification.object as! MessageModel
            if (model.roleId == nil || model.roleId != String(0)){
                return
            }
            DispatchQueue.main.async{
                viewModel.refreshVip()
                if viewModel.isVip {
                    self.isShowingDetailView = true
                    self.image = model.message
                } else {
                    showVIP.toggle()
                }
            }
        }
        .fullScreenCover(isPresented: $showVIP, content: {
            VipView(viewModel: .init(from: viewModel.logFrom))
        })
        .onChange(of: isFocused, perform: { _ in
            hasMsg = newMessage != ""
        })
    }

    func hideToastAfterDelay() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
            withAnimation {
                showMsgToast.toggle()
            }
        }
    }

    var featuresView: some View {
        return VStack(alignment: .center, spacing: 0) {
            Button {
                viewModel.logTranslateClick()
                self.showWhiteView = false
                showTranslateView = true

            } label: {
                HStack(alignment: .center, spacing: 0) {
                    // Body/Regular
                    Text(String.i18nText("feature_translate"))
                        .font(Font.custom("SF Pro", size: 17))
                        .foregroundColor(.black)
                        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
                    Text("✍️")
                        .font(Font.custom("SF Pro", size: 17))
                        .multilineTextAlignment(.center)
                        .foregroundColor(.black)
                        .frame(minWidth: 20, maxWidth: 20, maxHeight: .infinity, alignment: .center)
                }
                .padding(.horizontal, 16)
                .padding(.vertical, 0)
                .frame(maxWidth: .infinity, minHeight: 44, maxHeight: 44, alignment: .leading)
                .background(.white)
                .overlay(
                    Rectangle()
                        .inset(by: 0.25)
                        .stroke(Color(red: 0.07, green: 0.07, blue: 0.07).opacity(0.25), lineWidth: 0.5)
                )
            }

            Button {
                viewModel.logEmojiClick()
                self.showWhiteView = false
                showEmojiView = true
            } label: {
                HStack(alignment: .center, spacing: 0) {
                    // Body/Regular
                    Text(String.i18nText("feature_get_emoji"))
                        .font(Font.custom("SF Pro", size: 17))
                        .foregroundColor(.black)
                        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
                    Text("🥰")
                        .font(Font.custom("SF Pro", size: 17))
                        .multilineTextAlignment(.center)
                        .foregroundColor(.black)
                        .frame(minWidth: 20, maxWidth: 20, maxHeight: .infinity, alignment: .center)
                }
                .padding(.horizontal, 16)
                .padding(.vertical, 0)
                .frame(maxWidth: .infinity, minHeight: 44, maxHeight: 44, alignment: .leading)
                .background(.white)
                .overlay(
                    Rectangle()
                        .inset(by: 0.25)
                        .stroke(Color(red: 0.07, green: 0.07, blue: 0.07).opacity(0.25), lineWidth: 0.5)
                )
            }

            Button {
                viewModel.logDrawClick()
                self.showWhiteView = false
                showDrawImageView = true
            } label: {
                HStack(alignment: .center, spacing: 0) {
                    // Body/Regular
                    Text(String.i18nText("feature_draw_images"))
                        .font(Font.custom("SF Pro", size: 17))
                        .foregroundColor(.black)
                        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
                    Text("🎨")
                        .font(Font.custom("SF Pro", size: 17))
                        .multilineTextAlignment(.center)
                        .foregroundColor(.black)
                        .frame(minWidth: 20, maxWidth: 20, maxHeight: .infinity, alignment: .center)
                }
                .padding(.horizontal, 16)
                .padding(.vertical, 0)
                .frame(maxWidth: .infinity, minHeight: 44, maxHeight: 44, alignment: .leading)
                .background(.white)
                .overlay(
                    Rectangle()
                        .inset(by: 0.25)
                        .stroke(Color(red: 0.07, green: 0.07, blue: 0.07).opacity(0.25), lineWidth: 0.5)
                )
            }

            Button {
                viewModel.logRecognizeClick()
                self.showWhiteView = false
                showRecognizeImagesView = true
            } label: {
                HStack(alignment: .center, spacing: 0) {
                    // Body/Regular
                    Text(String.i18nText("feature_recognize"))
                        .font(Font.custom("SF Pro", size: 17))
                        .foregroundColor(.black)
                        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
                    Text("📷")
                        .font(Font.custom("SF Pro", size: 17))
                        .multilineTextAlignment(.center)
                        .foregroundColor(.black)
                        .frame(minWidth: 20, maxWidth: 20, maxHeight: .infinity, alignment: .center)
                }
                .padding(.horizontal, 16)
                .padding(.vertical, 0)
                .frame(maxWidth: .infinity, minHeight: 44, maxHeight: 44, alignment: .leading)
                .background(.white)
                .overlay(
                    Rectangle()
                        .inset(by: 0.25)
                        .stroke(Color(red: 0.07, green: 0.07, blue: 0.07).opacity(0.25), lineWidth: 0.5)
                )
            }

            Button {
                viewModel.logSummarizeClick()
                self.showWhiteView = false
                showSummarizeDocumentView = true

            } label: {
                HStack(alignment: .center, spacing: 0) {
                    // Body/Regular
                    Text(String.i18nText("feature_summarize"))
                        .font(Font.custom("SF Pro", size: 17))
                        .foregroundColor(.black)
                        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
                    Text("📄")
                        .font(Font.custom("SF Pro", size: 17))
                        .multilineTextAlignment(.center)
                        .foregroundColor(.black)
                        .frame(minWidth: 20, maxWidth: 20, maxHeight: .infinity, alignment: .center)
                }
                .padding(.horizontal, 16)
                .padding(.vertical, 0)
                .frame(maxWidth: .infinity, minHeight: 44, maxHeight: 44, alignment: .leading)
                .background(.white)
                .overlay(
                    Rectangle()
                        .inset(by: 0.25)
                        .stroke(Color(red: 0.07, green: 0.07, blue: 0.07).opacity(0.25), lineWidth: 0.5)
                )
            }

            Button {
                viewModel.logAnalyzeClick()
                self.showWhiteView = false
                showAnalyzeLinkView = true
            } label: {
                HStack(alignment: .center, spacing: 0) {
                    // Body/Regular
                    Text(String.i18nText("feature_link"))
                        .font(Font.custom("SF Pro", size: 17))
                        .foregroundColor(.black)
                        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
                    Text("🔗")
                        .font(Font.custom("SF Pro", size: 17))
                        .multilineTextAlignment(.center)
                        .foregroundColor(.black)
                        .frame(minWidth: 20, maxWidth: 20, maxHeight: .infinity, alignment: .center)
                }
                .padding(.horizontal, 16)
                .padding(.vertical, 0)
                .frame(maxWidth: .infinity, minHeight: 44, maxHeight: 44, alignment: .leading)
                .background(.white)
                .overlay(
                    Rectangle()
                        .inset(by: 0.25)
                        .stroke(Color(red: 0.07, green: 0.07, blue: 0.07).opacity(0.25), lineWidth: 0.5)
                )
            }
        }
        .padding(0)
        .frame(width: 192, alignment: .topLeading)
        .background(Color(red: 0.22, green: 0.22, blue: 0.22))

        .background(Color(red: 0.7, green: 0.7, blue: 0.7).opacity(0.82))

        .cornerRadius(12)
        .offset(whiteViewOffset)
        .onAppear {
            // 设置白色视图的位置
            whiteViewOffset = CGSize(width: 20, height: -55)
        }
    }

    var modeView: some View {
        return VStack(alignment: .leading, spacing: 0.5) {
            HStack(alignment: .center, spacing: 1) {
                if viewModel.mode == "gpt3" {
                    Text("✔️")
                        .font(
                            Font.custom("SF Pro", size: 17)
                                .weight(.semibold)
                        )
                        .multilineTextAlignment(.center)
                        .foregroundColor(.black)
                        .frame(minWidth: 24, maxWidth: 24, maxHeight: .infinity, alignment: .center)
                } else {
                    Text("")
                        .font(
                            Font.custom("SF Pro", size: 17)
                                .weight(.semibold)
                        )
                        .multilineTextAlignment(.center)
                        .foregroundColor(.black)
                        .frame(minWidth: 24, maxWidth: 24, maxHeight: .infinity, alignment: .center)
                }
                Text("GPT 3.5")
                    .font(Font.custom("SF Pro", size: 17))
                    .foregroundColor(.black)
                    .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
                Text("⚡️")
                    .font(Font.custom("SF Pro", size: 17))
                    .multilineTextAlignment(.center)
                    .foregroundColor(.black)
                    .frame(minWidth: 20, maxWidth: 20, maxHeight: .infinity, alignment: .center)
            }
            .padding(.leading, 7)
            .padding(.trailing, 16)
            .padding(.vertical, 0)
            .frame(maxWidth: .infinity, minHeight: 44, maxHeight: 44, alignment: .center)
            .background(.white)
            .overlay(
                Rectangle()
                    .inset(by: 0.25)
                    .stroke(Color(red: 0.07, green: 0.07, blue: 0.07).opacity(0.25), lineWidth: 0.5)
            ).onTapGesture {
                viewModel.logToGpt3Click()
                viewModel.mode = "gpt3"
                UserDefaults.standard.setValue("gpt3", forKey: "mode")
                UserDefaults.standard.synchronize()
                showModeView = false
            }
            HStack(alignment: .center, spacing: 1) {
                if viewModel.mode == "gpt4" {
                    Text("✔️")
                        .font(
                            Font.custom("SF Pro", size: 17)
                                .weight(.semibold)
                        )
                        .multilineTextAlignment(.center)
                        .foregroundColor(.black)
                        .frame(minWidth: 24, maxWidth: 24, maxHeight: .infinity, alignment: .center)
                } else {
                    Text("")
                        .font(
                            Font.custom("SF Pro", size: 17)
                                .weight(.semibold)
                        )
                        .multilineTextAlignment(.center)
                        .foregroundColor(.black)
                        .frame(minWidth: 24, maxWidth: 24, maxHeight: .infinity, alignment: .center)
                }
                Text("GPT 4.0")
                    .font(Font.custom("SF Pro", size: 17))
                    .foregroundColor(.black)
                    .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
                Text("🌟")
                    .font(Font.custom("SF Pro", size: 17))
                    .multilineTextAlignment(.center)
                    .foregroundColor(.black)
                    .frame(minWidth: 20, maxWidth: 20, maxHeight: .infinity, alignment: .center)
            }
            .padding(.leading, 7)
            .padding(.trailing, 16)
            .padding(.vertical, 0)
            .frame(maxWidth: .infinity, minHeight: 44, maxHeight: 44, alignment: .center)
            .background(.white)
            .overlay(
                Rectangle()
                    .inset(by: 0.25)
                    .stroke(Color(red: 0.07, green: 0.07, blue: 0.07).opacity(0.25), lineWidth: 0.5)
            ).onTapGesture {
                showModeView = false
                if !viewModel.isVip {
                    showVIP.toggle()
                } else {
                    viewModel.logToGpt4Click()
                    viewModel.mode = "gpt4"
                    UserDefaults.standard.setValue("gpt4", forKey: "mode")
                    UserDefaults.standard.synchronize()
                }
            }
        }
        .padding(0)
        .frame(width: 194, alignment: .topLeading)
        .background(Color(red: 0.22, green: 0.22, blue: 0.22))
        .background(Color(red: 0.7, green: 0.7, blue: 0.7).opacity(0.82))
        .cornerRadius(12)
        .shadow(color: .black.opacity(0.2), radius: 16, x: 0, y: 0)
        .offset(modeViewOffset)
        .onAppear {
            modeViewOffset = CGSize(width: 90, height: -44)
            viewModel.mode = UserDefaults.standard.string(forKey: "mode") ?? "gpt3"
        }
    }
}

#Preview {
    HomePageView(section: .constant(.first), item: .constant(.init(text: "")), historyItemRoleId: .constant(0))
}
